import { CodeTypeError } from "@iuijs/helper/es/http.request";
import { UserStatusService } from "@iuijs/helper/es/user-status.service";
import qs from "qs";

// import { environment } from "@src/environments";
/**
 * PMS 系统用户状态管理
 */
export class OaUserService extends UserStatusService {
  // 响应拦截，统一处理返回值
  interceptResponse(res) {
    if(res.config.responseType==='blob') return res;
    if (res.status == 200 && res.data && res.data.result == 'ok') {
      return res.data.data;
    } else if ('errorCode' in res.data) {
      if (res.data.data && res.data.data.desc.indexOf('失效')) {
        this.logout();
      }
      throw new CodeTypeError(res.data.errorCode, res.data.data.desc);
    }else if(res.data.result==='error'){
      throw new CodeTypeError(res.data.id, res.data.msg)
    } else {
      throw new CodeTypeError('999999', '数据响应格式错误');
    }
  }
  logout(){
    super.logout();
    window.location.href='/portal/';
  }
  /**
   * 设置登录状态
   * @param data 传入的用户状态信息
   */
  login(data) {
    super.login(data);
    // this.setHeader('Authorization', `${data.token.tokenType} ${data.token.accessToken}`);
    // pmsUserService.setHeader('sid', data.token);
  }
  isLogined() {
    return this.data && this.data.token;
  }
  /**
   * 重写POST请求以适应OA后端接口
   */
  post(path, data, options){
    options = Object.assign({
      headers: {
        'Content-Type': "application/x-www-form-urlencoded"
      },
      params:{}
    },options);
    options.params.sid = this.data.sid;
    return super.post(path, qs.stringify(data), options);
  }
  get(path, params, options){
    options = Object.assign({
      headers: {
        'Content-Type': "application/x-www-form-urlencoded"
      },
      params:params
    },options);
    options.params.sid = this.data.sid;
    return super.get(path, options.params, options);
  }
  /**
   * 重写createUrl
   */
  createUrl(path, params){
    return super.createUrl(path, params).replace(/\?$/,'');
  }
}
